# -*- coding: utf-8 -*-
"""
Created on Mon Aug 14 10:06:18 2017

@author: za-huchenkai
"""
#from importlib import reload

import numpy as np
import pandas as pd
import scipy.optimize as opt
import json
import os
import time
import pymongo
# connection=pymongo.MongoClient('10.253.109.137',27017)


import sys
reload(sys) 
sys.setdefaultencoding('utf8')

def bl(dparam):
    # f="in.json"

    a=[3,1,9,1,3,0,0,0,1,1,1,1]
    b=[7,3,7,3,5,3,3,3,5,3,3,5]
    c=[9,5,5,7,7,5,5,5,7,7,7,7]
    d=[5,7,3,0,9,7,7,7,9,9,9,0]
    e=[1,9,1,0,0,9,0,0,0,0,0,0]
    assess={'a':a,'b':b,'c':c,'d':d,'e':e}
    assess=pd.DataFrame(assess,index=[range(1,13)])

    ###11~36 37~72 73~100

    # load_f=file(f,'r')
    # d = json.loads(load_f.read())
    # load_f.close()

    answer=dparam['answerList']
    answer=pd.DataFrame(answer)
    fen=[]
    for i in range(len(answer)):
    #    print i
    #    print answer['answer'][i]
    #    print answer['questionId'][i]-1
        feni=assess[answer['answer'][i]][answer['questionId'][i]]
        fen.append(feni)
    fen=np.sum(fen)

    if fen<=36:
        alpha=2
    elif fen<=72:
        alpha=1
    else:
        alpha=0.5

    asset=dparam['assetsList']

    def hebing():
        result=pd.DataFrame(asset[0]['priceList'])
        for a in asset[1:]:
            x=pd.DataFrame(a['priceList'])
            #df=x['price']
            #df.index=x['dt']
            result=result.merge(x,on='dt',how='inner')
        return result

    result=hebing()
    result=np.mat(result.iloc[0:,1:])
    x=result.astype(float)
    x=(x[1:,]/x[0:(np.shape(x)[0]-1),]-1)

    xvcv=np.mat(np.cov(x.T))
    p=x.mean(axis=0)
    p=np.array(p)[0]

    def utility(w,p,alpha):
        return -np.dot(w,p)+alpha*float(np.mat(w)*xvcv*np.mat(w).T)

    def utility_constraints(w,p,alpha):
        con=[]
        for i in range(len(asset)):
            con1=eval('w['+str(i)+']')
            con.append(con1)
        con1=str()
        for i in range(len(asset)):
            con1=con1+'w['+str(i)+']+'
        con2=con1+'1'
        con.append(eval(con2))
        con1=str()
        for i in range(len(asset)):
            con1=con1+'-w['+str(i)+']'
        con3=con1+'+1'
        con.append(eval(con3))
        return np.array(con)


    #def utility_constraints(w,p,alpha):
    #
    #    return np.array(w)




    w0=np.array([1./len(asset)]*len(asset))
    u=opt.fmin_slsqp(utility,w0,f_ieqcons=utility_constraints,args=(p,alpha),bounds=[(0,0.5)]*len(asset))
    u=np.round(u*100,2)


    zichan=[]
    for a in asset:
        zichan.append(a['assetsName'])
    zichan=np.array(zichan)

    day=time.strftime('%Y-%m-%d', time.localtime(time.time()))

    out_dict=[]
    for i in range(len(u)):
        dic={'assetsName': zichan[i],
             'dt':day,
             'proportion':u[i]}
        out_dict.append(dic)

    out=json.dumps((out_dict), indent=4, sort_keys=True, ensure_ascii=False)

    # f_out='out.json'
    # dump_f=open(f_out,'w')
    # dump_f.write(out)
    # dump_f.close()
    return out









